<?php
/**
 * (jobs) 物流运输费用
 */
namespace App\Jobs\Basics;

use App\Models\Basics\SysICountry;
use App\Models\Operation\ProfitSku;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class TransportFeeRelate implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $areaId;
    protected $airFee;
    protected $seaFee;

    /**
     * TransportFeeRelate constructor.
     * @param $areaId
     * @param $airFee
     * @param $seaFee
     */
    public function __construct($areaId,$airFee,$seaFee)
    {
        $this->areaId = $areaId;
        $this->airFee = $airFee;
        $this->seaFee = $seaFee;
    }

    /**
     * Execute the job.
     * @return void
     */
    public function handle()
    {
        $this->exeFillData($this->areaId,$this->airFee,$this->seaFee);
    }

    //更新毛利率表
    private function exeFillData($areaId,$airFee,$seaFee){
        $countryIds = SysICountry::getCountryIdsByAreaId($areaId);
        ProfitSku::query()->whereIn('country_id',$countryIds)->orderBy('id')
            ->chunk(500,function ($item) use ($airFee,$seaFee){
                foreach ($item as $_item){
                    $fee = $_item->transport == 1 ? $seaFee : $airFee;
                    $_item->head_cost = round($_item->weight * $fee / $_item->rate_odds,3);
                    $tpl = round($_item->tpl_rmb / $_item->rate_odds,3);
                    $_item->cost = ProfitSku::getCost($tpl,$_item->sale_price,$_item->head_cost,$_item->fba_fee,$_item->commission,$_item->return,$_item->vat);
                    $_item->profit = round($_item->sale_price - $_item->cost,3);
                    $_item->profit_rate = $_item->sale_price == 0 ? 0 : round($_item->profit / $_item->sale_price,3);
                    $_item->save();
                }
            });
    }
}
